package com.neo.push.server.connection;

import com.neo.push.server.PushServer;
import com.neo.push.server.SafetyMessageTask;
import com.neo.push.server.listener.ServerListener;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * Created by lock on 17-8-2.
 */
public class HashedWheelMessageTimer implements SafetyMessageTimer,ServerListener {


    private final HashedWheelTimer wheelTimer = new HashedWheelTimer();
    private final Map<String,Timeout> timeoutContext = new ConcurrentHashMap<>();
    private Logger logger = LoggerFactory.getLogger(HashedWheelMessageTimer.class);

    private void startTimer(){
        wheelTimer.start();
    }

    private void stopTimer(){
        wheelTimer.stop();
    }



    @Override
    public  Timeout addTask(SafetyMessageTask task, long delay, TimeUnit unit){
        return timeoutContext.putIfAbsent(task.messageId(),wheelTimer.newTimeout(task,delay,unit));
    }

    @Override
    public Timeout removeTimeout(String messageId) {
        return timeoutContext.remove(messageId);
    }

    @Override
    public void serverStarted(PushServer pushServer) {
        startTimer();
        logger.info(" hashed wheel message timer started ! ");
    }

    @Override
    public void serverClosed(PushServer pushServer) {
        stopTimer();
        logger.info(" hashed wheel message timer closed ! ");
    }
}
